<template>
  <div style="padding: 20px;">
    <div class="topLocation">出入库记录管理 / 记录管理</div>
    <div class="topTool">
      <div class="group">货物名称：</div>
      <el-input v-model="searchGoodsName" placeholder="请输入货物名称" style="margin-right: 50px;"></el-input>
      <div class="group">仓库名称：</div>
      <el-input v-model="searchWarehouseName" placeholder="请输入仓库名称" style="margin-right: 50px;"></el-input>
      <div class="group">操作类型：</div>
      <el-select v-model="searchActionType" placeholder="请选择操作类型" style="margin-right: 50px;">
        <el-option label="入库" value="入库"></el-option>
        <el-option label="出库" value="出库"></el-option>
        <el-option label="所有操作" value=""></el-option>
      </el-select>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除选中记录</el-button>
    </div>
    <el-table
        :data="recordData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="goodsName" label="货物名称"></el-table-column>
      <el-table-column prop="warehouseName" label="仓库名称"></el-table-column>
      <el-table-column prop="category" label="货物类别"></el-table-column>
      <el-table-column prop="operator" label="操作人"></el-table-column>
      <el-table-column prop="applicant" label="申请人"></el-table-column>
      <el-table-column prop="actionType" label="操作类型"></el-table-column>
      <el-table-column prop="quantity" label="操作数量"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 编辑记录的对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="备注">
          <el-input v-model="form.remark" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogOk">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Search } from "@element-plus/icons-vue";

const recordData = ref([]); // 记录数据
const currentPage = ref(1); // 当前页数
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总记录数
const searchGoodsName = ref(''); // 货物名称搜索关键字
const searchWarehouseName = ref(''); // 仓库名称搜索关键字
const searchActionType = ref(''); // 操作类型搜索关键字

const formatDate = (row, column, cellValue, index) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1);
  const day = date.getDate();
  const pad = (num) => num < 10 ? '0' + num : num;
  return `${year}-${pad(month)}-${pad(day)}`;
};

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/record/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      goodsName: searchGoodsName.value,
      warehouseName: searchWarehouseName.value,
      actionType: searchActionType.value
    }
  }).then(response => {
    recordData.value = response.data.data.records;
    total.value = response.data.data.total;
  }).catch(error => {
    console.error(error);
  });
};

onMounted(() => {
  getData();
});

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `您确定要删除记录【${row.goodsName}】的操作吗?`,
      '危险操作'
  ).then(() => {
    delRecord(row.id);
    ElMessage({
      type: 'success',
      message: '删除成功!',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

const delRecord = (recordId) => {
  axios.delete(`http://localhost:8080/record/${recordId}`)
      .then(() => {
        getData();
      })
      .catch((error) => {
        console.error(error);
      });
};

const handleSearch = () => {
  const params = {
    goodsName: searchGoodsName.value || null,      // 货物名称
    warehouseName: searchWarehouseName.value || null,  // 仓库名称
    actionType: searchActionType.value || null     // 操作类型
  };
  // 发送请求到后端
  axios.get('http://localhost:8080/record/search', { params })
      .then(response => {
        // 更新前端的记录数据
        recordData.value = response.data.data;
      })
      .catch(error => {
        // 错误处理
        console.error(error);
        ElMessage.error('查询失败');
      });
};

const handleSortChange = (sortData) => {
  const { prop, order } = sortData;
  recordData.value = recordData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

let multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => item.id);
};

const handleDelList = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的记录！');
    return;
  }
  ElMessageBox.confirm(
      "您确定要删除选中的记录？",
      '危险操作'
  ).then(() => {
    multipleSelection.value.forEach((id) => {
      delRecord(id);
    });
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!'
    });
  });
};

const dialogFormVisible = ref(false);
const dialogTitle = ref('编辑记录');
const form = ref({
  id: null,
  goodsName: '',
  warehouseName: '',
  category: '',
  operator: '',
  applicant: '',
  actionType: '',
  quantity: null,
  remark: ''
});

const handleEdit = (row) => {
  dialogTitle.value = '编辑记录';
  form.value = { ...row }; // 编辑时填充当前行数据
  dialogFormVisible.value = true;
};

const dialogOk = () => {
  // 表单验证，确保备注有值
  if (!form.value.remark) {
    ElMessage.error('备注不能为空');
    return; // 阻止后续操作
  }

  // 编辑记录
  axios.put(`http://localhost:8080/record/${form.value.id}`, form.value)
      .then(() => {
        dialogFormVisible.value = false; // 关闭弹窗
        getData(); // 刷新数据
        ElMessage.success('记录编辑成功');
      })
      .catch((error) => {
        console.error(error);
        ElMessage.error('编辑失败');
      });
};
</script>
<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px;     /* 设置字体大小为 14px */
}
</style>
